package cn.ifavor.googleplay.fragment;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.text.format.Formatter;
import android.view.View;
import cn.ifavor.googleplay.DetailActivity;
import cn.ifavor.googleplay.R;
import cn.ifavor.googleplay.adapter.DefaultAdapter;
import cn.ifavor.googleplay.base.BaseFragment;
import cn.ifavor.googleplay.base.BaseViewHolder;
import cn.ifavor.googleplay.constants.URLConstant;
import cn.ifavor.googleplay.domain.AppInfo;
import cn.ifavor.googleplay.utils.UiUtils;
import cn.ifavor.googleplay.view.BaseListView;

public class AppFragment extends BaseFragment {

	private List<AppInfo> mDatas;

	@Override
	protected View createSuccessView() {
		BaseListView mList = new BaseListView(UiUtils.getContext());

		mList.setAdapter(new DefaultAdapter<AppInfo>(mDatas, R.layout.item_appinfo, mList){
			@Override
			public void setHolder(BaseViewHolder<AppInfo> holder, AppInfo data) {
				String imageURL = URLConstant.baseURL + "/image?name="+ data.getIconurl();
				holder.setImage(R.id.item_icon, imageURL);
				holder.setText(R.id.item_title, data.getName());
				holder.setText(R.id.item_size,Formatter.formatFileSize(UiUtils.getContext(),data.getSize()));
				holder.setText(R.id.item_bottom, data.getDes());
			}

			@Override
			protected String getUrl(int index) {
				return AppFragment.this.getURL(index);
			}

			@Override
			protected List<AppInfo> onParse(String result) {
				parse(result);
				return mDatas;
			}
			
			@Override
			public void onItemClickListener(int location, List<AppInfo> datas) {
				super.onItemClickListener(location, datas);
				
				Bundle bundle = new Bundle();
				bundle.putString("package", datas.get(location).getPackagename());
				UiUtils.startActivity(getActivity(), DetailActivity.class, bundle);
			}
		});
		return mList;
	}

	@Override
	protected String getURL(int index) {
		return URLConstant.baseURL + "/app?index="+index;
	}

	@Override
	protected void parse(String result) {
		mDatas = new ArrayList<AppInfo>();
		try {
			JSONArray array = new JSONArray(result);
			if (array != null && array.length() > 0) {
				for (int i = 0; i < array.length(); i++) {
					JSONObject obj2 = array.optJSONObject(i);
					AppInfo info = new AppInfo();

					info.setId(obj2.optInt("id"));
					info.setName(obj2.optString("name"));
					info.setPackagename(obj2.optString("packageName"));
					info.setIconurl(obj2.optString("iconUrl"));
					info.setStars((float) obj2.optDouble("stars"));
					info.setSize(obj2.optInt("size"));
					info.setDownloadurl(obj2.optString("downloadUrl"));
					info.setDes(obj2.optString("des"));

					mDatas.add(info);
				}
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void loadCache(String cache) {
		parse(cache);
	}
}
